package com.lxyk.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxyk.mapper.WorkerMapper;
import com.lxyk.pojo.Customer;
import com.lxyk.pojo.History;
import com.lxyk.pojo.Worker;
import com.lxyk.service.CustomerService;
import com.lxyk.service.HistoryService;
import com.lxyk.service.WorkerService;
import com.lxyk.vo.MainMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.applet.Main;

import java.util.*;

@RequestMapping("/history")
@Controller
@Slf4j
public class HistoryController {
    @Autowired
    private  HistoryService historyService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     点击“送水历史管理”，调用HistoryService对象查询所有送水历史信息，然后将信息渲染到前端。最后返回“送水历史”页面
     */
    @RequestMapping("/listHis")
    public String listHistory(Model model,@RequestParam Map<String ,Object> map,
                              @RequestParam(required = false,defaultValue = "1",value = "pageNum")Integer pageNum,
                              @RequestParam(defaultValue = "10",value = "pageSize")Integer pageSize){
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<History> pageInfo = historyService.listHistory(map, pageNum, pageSize);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("pageNo",pageInfo.getPageNum()); //页号
        model.addAttribute("totalPages",pageInfo.getPages()); //总页数
        model.addAttribute("pageNums",pageInfo.getNavigatepageNums()); //有导航页码数
        return "historyList";


    }
    /**
     点击“添加”按钮执行预修改操作
     步骤：
     1 查询客户列表和送水工列表
     2 将客户列表和送水工列表渲染到前端页面
     3 返回送水历史页面
     */
    @RequestMapping("/preSaveHis")
    public String preSaveHistory(Model model){
        List<Customer> custList = customerService.list();
        List<Worker> workerList = workerService.list();
        model.addAttribute("custList",custList);
        model.addAttribute("workerList",workerList);
        return "historySave";

    }


    @PostMapping("/saveHis")
    public String saveHistory(History history,Integer workerId,Integer custId){
        Worker worker = new Worker();
        worker.setWid(workerId);

        Customer cust = new Customer();
        cust.setCid(custId);

        log.info(cust.getCid()+"------------");

        history.setWorker(worker);
        history.setCustomer(cust);
        historyService.save(history);

        //清空redis
        redisTemplate.delete("mainMenu");
        //查询再次设置到redis进行排序
        List<MainMenu> mainMenu = new ArrayList<>();
        List<MainMenu> list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        historyService.list().forEach(h ->{
            map.put(h.getWorkerId(),map.getOrDefault(h.getWorkerId(),0)+h.getSendWaterCount());
        });
        workerService.list().forEach(e -> {
            MainMenu main = new MainMenu();
            main.setWorkerName(e.getWorkerName());
            Integer count = map.get(e.getWid());
            main.setSendWaterCount(count == null ? 0 : count);
            list.add(main);
        });

        Collections.sort(list, (o1, o2) ->{
            if(o1.getSendWaterCount() > o2.getSendWaterCount()){
                return 1;
            }else if (o1.getSendWaterCount()  < o2.getSendWaterCount()){
                return -1;
            }else {
                return 0;
            }
        });
        if (list.size() < 12){
            mainMenu.addAll(list);
        }
        for (int i = list.size() - 12; i < list.size(); i++) {
            mainMenu.add(list.get(i));
        }
        redisTemplate.opsForList().leftPushAll("mainMenu",mainMenu);
        return "redirect:/history/listHis";
    }
    /*
    * 点击到修改页面
    * */
    @RequestMapping("/preUpdateHis/{hid}")
    public String preUpdateHis(Model model, @PathVariable("hid") Integer hid){
        List<Customer> custList = customerService.list();
        List<Worker> workerList = workerService.list();
        History history = historyService.getHistoryById(hid);
        model.addAttribute("custList",custList);
        model.addAttribute("workerList",workerList);
        model.addAttribute("history",history);
        return "historyUpdate";
    }
    /*
    * 修改页面
    * */
    @PostMapping("/updateHis")
    public String updateHistory(History history,Integer workerId,Integer custId){
        Worker worker = new Worker();
        worker.setWid(workerId);
        Customer customer = new Customer();
        customer.setCid(custId);
        history.setWorker(worker);
        history.setCustomer(customer);
        //调用修改方法
        historyService.updateHistory(history);

        return "redirect:/history/listHis";




    }
    /**
     * 处理批量删除请求
     * @param idList 前端传入的要删除的送水历史id列表
     * @return OK 批量删除成功，Fail表示批量删除失败
     */
    @RequestMapping("/batchDeleteHistory")
    @ResponseBody
    public String batchDeleteHistory(String idList){
        //调用业务逻辑层方法进行删除
        int rows = historyService.batchDeleteHistory(idList);
        if (rows > 0){
            return "OK";
        }else {
            return "Fail";
        }

    }
}
